package com.czy.owner.ui;

import android.content.Intent;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.czy.owner.R;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.WebViewRequestParam;
import com.czy.owner.global.Constants;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.hotshop.GoodsDetailActivity;
import com.czy.owner.ui.hotshop.GoodsListActivity;
import com.czy.owner.ui.information.PriceRatioDetailActivity;
import com.czy.owner.ui.login.LoginActivity;
import com.czy.owner.ui.parity.ParityActivity;
import com.czy.owner.utils.AssetsFileUtils;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.ShareUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.widget.UniversalDialog;

import java.net.CookieManager;
import java.net.URLDecoder;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;

/**
 * Created by King on 2016/10/26 0026.
 */

public class WebViewActivity extends BaseActivity {
    @BindView(R.id.webview)
    WebView webview;
    @BindView(R.id.myProgressBar)
    ProgressBar myProgressBar;
    private WebViewRequestParam webViewRequestParam;
    private int myType = 0;

    private String postDate;
    private String url;
    private String mPattern = "哈哈哈哈哈哈";
    private String checkType = "袋鼠管家";
    public static int bindStoreId = 0;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_webview;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        checkType = getIntent().getStringExtra("type");
        MyLog.e("yang", "type==" + checkType);
        webViewRequestParam = (WebViewRequestParam) getIntent().getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY);
//        webview.setWebViewClient(new MyWebViewClient());
        WebSettings ws = webview.getSettings();
        ws.setJavaScriptEnabled(true);
        ws.setUseWideViewPort(false);
        ws.setCacheMode(WebSettings.LOAD_NO_CACHE);
        ws.setDomStorageEnabled(true);
        ws.setLoadWithOverviewMode(true);
        ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        ws.setSupportZoom(true);
        if (checkType != null) {
            if (checkType.equals("preferential")) {
                getToolbarTitle().setText("特惠商品");
            } else if (checkType.equals("growth")) {
                getToolbarTitle().setText("升级规则");
                webview.postUrl(webViewRequestParam.getUrl(), webViewRequestParam.getParams().getBytes());
            } else if (checkType.equals("h5")) {
                getToolbarTitle().setText("车品展销会");
                webview.postUrl(webViewRequestParam.getUrl(), webViewRequestParam.getParams().getBytes());
            } else if (checkType.equals("url")) {
                getToolbarTitle().setText(getIntent().getStringExtra("title"));
                webview.postUrl(webViewRequestParam.getUrl(), webViewRequestParam.getParams().getBytes());
            } else if (checkType.equals("doubleEleven")) {
                getToolbarTitle().setText("双十一活动");
                postDate = "session=" + UserHelper.getInstance().getSession(WebViewActivity.this) + "&flag=false";
                url = Constants.APP_API_BASE + Constants.OWN_SHOP_DOUBLEELEVEN;
                webview.postUrl(url, postDate.getBytes());
            } else {
                webview.loadUrl(webViewRequestParam.getUrl() + "?" + webViewRequestParam.getParams().getBytes());
                if (webViewRequestParam.getUrl().contains("priceRatio")) {
                    getToolbarTitle().setText("比价活动");
                    MyLog.e("yang","比价活动比价活动比价活动比价活动");
                }
            }
        } else {
            try {
                String title = getIntent().getStringExtra("title");
                MyLog.e("yang", "title=" + title);
                if (!TextUtils.isEmpty(title)) {
                    getToolbarTitle().setText(title);
                } else {
                    //不设置title
                }
            } catch (Exception e) {
                MyLog.e("yang", "e==" + e.toString());
            }

            webview.loadUrl(webViewRequestParam.getUrl() + "?" + webViewRequestParam.getParams().getBytes());
        }


//        http://118.178.188.69/own/shop/priceRatio/info?infoId=2686
//        http://118.178.188.69/pub/goodsView?goodsId=1053
        webview.setWebViewClient(new WebViewClient() {
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                return super.shouldOverrideUrlLoading(view, url);
//            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, final WebResourceRequest request) {
                MyLog.e("yang", request.getUrl().toString());
                if (request.getUrl().toString().contains("own/shop/priceRatio/info?infoId")) {
                    mPattern = "priceRatio/info\\?infoId=(\\d*?)$";
                    MyLog.e("yang", "比价活动");
                    myType = 0;
                } else if (request.getUrl().toString().contains("pub/goodsView?goodsId")) {
                    mPattern = "pub/goodsView\\?goodsId=(\\d*?)$";
                    MyLog.e("yang", "商品");
                    myType = 1;
                } else if (request.getUrl().toString().contains("own/shop/priceRatio?joinType")) {
                    String joinTypeUrl = request.getUrl().toString();
                    MyLog.e("yang", "joinTypeUrl===" + joinTypeUrl);
                    String joinTypeIds = joinTypeUrl.substring(joinTypeUrl.indexOf("=") + 1, joinTypeUrl.indexOf("&"));
                    String goodsActivityIds = joinTypeUrl.substring(joinTypeUrl.lastIndexOf("=") + 1);
                    MyLog.e("yang", "goodsActivityIds==" + goodsActivityIds + "\njoinTypeIds==" + joinTypeIds);
                    //TODO 立即参与
                    Intent intent = new Intent(WebViewActivity.this, ParityActivity.class);
                    intent.putExtra("goodsActivityId", goodsActivityIds);
                    startActivity(intent);

                } else if (request.getUrl().toString().contains("hot/goodsList")) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            webview.stopLoading();
                            startActivity(new Intent(WebViewActivity.this, HotCarProductActivity.class));
                        }

                    });
//                    双11活动门店id
                } else if (request.getUrl().toString().contains("sto/store?storeId")) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            int storeId = (int) SharedPreferencesUtils.getParam(WebViewActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0);
                            webview.stopLoading();
                            String storeUrl = request.getUrl().toString();
                            String mStoreId = storeUrl.substring(storeUrl.lastIndexOf("=") + 1);
                            MyLog.e("yang", "mStoreId==" + mStoreId);
                            if (!UserHelper.getInstance().isLogined()) {
                                MyLog.e("yang", "未登录");
                                helpDialog("温馨提示", "立即登录参与门店活动", "确定", "取消", 1, 0);
                            } else {
                                //  登录未绑定
                                if (storeId == 0) {
                                    MyLog.e("yang", "登录未绑定");
                                    helpDialog("温馨提示", "绑定该门店参与门店活动", "确定", "取消", 2, Integer.valueOf(mStoreId));
                                } else {
                                    // 登录绑定
                                    MyLog.e("yang", "登录绑定");
                                    finish();
                                    RxBus.getDefault().post(Constants.RXBUS_CODE_SWITCH_MAIN_TAB, new CommonEvent("登录绑定"));

                                }
                            }
                        }
//
                    });
                    //供应商商品
                } else if (request.getUrl().toString().contains("getSupGoodsList?supplierId")) {

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            String supplierName = request.getUrl().toString().substring(request.getUrl().toString().indexOf("=") + 1, request.getUrl().toString().indexOf("&"));
                            Map<String, String> mapRequest = PhoneUtils.URLRequest(request.getUrl().toString());
                            webview.stopLoading();
                            Intent ti7 = new Intent(WebViewActivity.this, GoodsListActivity.class);
                            ti7.putExtra("goodsType", 2);
                            ti7.putExtra("labels", "");
                            ti7.putExtra("supplierId", mapRequest.get("supplierid"));
                            ti7.putExtra("mFromType", Constants.GOODSSOURCE_STORE);
                            ti7.putExtra("mFromTypeId", "0");
                            try {
                                ti7.putExtra("title", URLDecoder.decode(mapRequest.get("suppliername").toUpperCase(), "UTF-8"));
                            } catch (Exception e) {
                                MyLog.e("yang", "转码异常" + mapRequest.get("suppliername"));

                            }
                            MyLog.e("yang", mapRequest.toString());
                            ti7.putExtra("goodsActivityId", mapRequest.get("goodsactivityid"));
                            startActivity(ti7);

                        }

                    });

                }
                //门店商品
                else if (request.getUrl().toString().contains("getStoreGoodsList?storeId")) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            Map<String, String> mapRequest = PhoneUtils.URLRequest(request.getUrl().toString());

                            webview.stopLoading();
                            Intent ti7 = new Intent(WebViewActivity.this, GoodsListActivity.class);
                            ti7.putExtra("goodsType", 3);
                            ti7.putExtra("labels", "");
                            ti7.putExtra("storeId", mapRequest.get("storeid"));
                            ti7.putExtra("goodsActivityId", mapRequest.get("goodsactivityid"));
                            try {
                                ti7.putExtra("title", URLDecoder.decode(mapRequest.get("storename").toUpperCase(), "UTF-8"));
                            } catch (Exception e) {

                            }
                            MyLog.e("yang", mapRequest.toString());
                            startActivity(ti7);

                        }

                    });

                }
                Pattern p = Pattern.compile(mPattern);
                Matcher m = p.matcher(request.getUrl().toString());
                while (m.find()) {
                    MyLog.e("yang", "***************************");
                    final String id = m.group(1);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            MyLog.e("yang", "id=======" + id);
                            webview.stopLoading();
                            switch (myType) {
                                case 0:
                                    if (Integer.parseInt(id) != 0) {
                                        Intent intent = new Intent(WebViewActivity.this, PriceRatioDetailActivity.class);
                                        intent.putExtra("infoId", Integer.parseInt(id));
                                        intent.putExtra("title", "详情");
                                        startActivity(intent);
                                    } else {
                                        PhoneUtils.ShowToastMessage(WebViewActivity.this, "暂无详情");
                                    }
                                    break;
                                case 1:
                                    Intent intent = new Intent(WebViewActivity.this, GoodsDetailActivity.class);
                                    intent.putExtra("goodsId", Integer.parseInt(id));
                                    if (checkType != null) {
                                        if (checkType.equals("preferential")) {
                                            intent.putExtra("mFromType", Constants.GOODSSOURCE_PREFERENCE);
                                        } else if (checkType.equals("doubleEleven")) {
                                            intent.putExtra("mFromType", Constants.GOODSSOURCE_DOUBLE);
                                        } else {
                                            intent.putExtra("mFromType", Constants.GOODSSOURCE_STORE);
                                        }
                                    } else {
                                        intent.putExtra("mFromType", Constants.GOODSSOURCE_STORE);
                                    }

                                    MyLog.e("yang", "webview===" + getIntent().getStringExtra("mFromTypeId"));


                                    if (!TextUtils.isEmpty(getIntent().getStringExtra("mFromTypeId"))) {
                                        intent.putExtra("mFromTypeId", getIntent().getStringExtra("mFromTypeId"));
                                    } else {
                                        intent.putExtra("mFromTypeId", "0");
                                    }

                                    startActivity(intent);
                                    break;


                            }


                        }
                    });


                    return null;
                }
                return super.shouldInterceptRequest(view, request);
            }


        });


        webview.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO Auto-generated method stub
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    if (myProgressBar != null) {
                        myProgressBar.setVisibility(View.GONE);
                    }
                    if (myProgressBar != null) {
                        myProgressBar.setVisibility(View.GONE);
                    }
                } else {
                    myProgressBar.setVisibility(View.VISIBLE);
                    myProgressBar.setProgress(newProgress);

                }
            }

        });
    }

    @Override
    protected void updateViews() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        webview.destroy();

        webview.setWebChromeClient(null);
        webview.setWebViewClient(null);
        webview.getSettings().setJavaScriptEnabled(false);
        webview.clearCache(true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (checkType != null) {
            if (checkType.equals("preferential")) {
                MyLog.e("yang", "onResume---");
                postDate = "goodsActivityId=" + webViewRequestParam.getUrl();
                url = Constants.APP_API_BASE + Constants.OWN_SHOP_PREFERENTIAL;
                webview.postUrl(url, postDate.getBytes());
            }
        }

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_information_detail_top, menu);
        MenuItem itemCollect = menu.findItem(R.id.img_collection);
        MenuItem itemShare = menu.findItem(R.id.icon_share);
        itemCollect.setVisible(false);
        if (!getToolbarTitle().getText().toString().equals("双十一活动")) {
            itemShare.setVisible(false);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        String imgUrl = "";

        switch (item.getItemId()) {
            case R.id.icon_share:
                if (TextUtils.isEmpty(imgUrl)) {
                    try {
                        AssetsFileUtils.getImageFromAssetsFile(WebViewActivity.this, "owner_share_icon.png");
                    } catch (Exception e) {

                    }
                    ShareUtils.showShare(WebViewActivity.this, null, false,
                            Constants.APP_API_BASE + Constants.OWN_SHOP_DOUBLEELEVEN + "?flag=true",
                            "袋鼠车管家",
                            "约惠双十一,养车狂欢节",
                            imgUrl,
                            Constants.APP_API_BASE + Constants.OWN_SHOP_DOUBLEELEVEN + "?flag=true");
                }


        }
        return super.onOptionsItemSelected(item);
    }

    private void helpDialog(String title, String msg, String sure, String cancle, final int type, final int mStoreId) {
        new UniversalDialog(WebViewActivity.this).builder()
                .setTitle(title)
                .setMsg(msg)
                .setPositiveButton(sure, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (type) {
                            case 1:
                                startActivity(new Intent(WebViewActivity.this, LoginActivity.class).putExtra(Constants.TRANSMISSION_CONTENT_KEY, false));
                                break;
                            case 2:
                                finish();
                                bindStoreId = mStoreId;
                                RxBus.getDefault().post(Constants.RXBUS_CODE_SWITCH_MAIN_TAB, new CommonEvent("登录未绑定"));
                                break;

                        }

                    }
                }).setNegativeButton(cancle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }

}
